<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Mixin模式的实现</title>
</head>
<body>
    <h1>Mixin模式的实现</h1>

    <script>
        // 基本的Mixin模式
        const mixinLogger = {
            log(message) {
                console.log(`[${new Date()}] ${message}`);
            }
        };

        const mixinEventEmitter = {
            eventHandlers: {},
            on(event, handler) {
                if (!this.eventHandlers[event]) {
                    this.eventHandlers[event] = [];
                }
                this.eventHandlers[event].push(handler);
            },
            emit(event, data) {
                const handlers = this.eventHandlers[event];
                if (handlers) {
                    handlers.forEach(handler => handler(data));
                }
            }
        };

        // 使用Mixin
        class User {
            constructor(name) {
                this.name = name;
            }
        }

        // 将Mixin混入类
        Object.assign(User.prototype, mixinLogger, mixinEventEmitter);

        const user = new User('张三');
        user.log('用户创建成功'); // [当前时间] 用户创建成功
        user.on('login', data => console.log('用户登录:', data));
        user.emit('login', { time: new Date() });

        // 更复杂的Mixin示例：可组合的行为
        const mixinTimestamp = {
            getTimestamp() {
                return new Date().getTime();
            }
        };

        const mixinStorage = {
            save(key, value) {
                localStorage.setItem(key, JSON.stringify(value));
            },
            load(key) {
                return JSON.parse(localStorage.getItem(key));
            }
        };

        class Task {
            constructor(title) {
                this.title = title;
            }
        }

        // 组合多个Mixin
        Object.assign(Task.prototype, 
            mixinLogger,
            mixinTimestamp,
            mixinStorage,
            mixinEventEmitter
        );

        const task = new Task('完成作业');
        task.log(`任务创建于 ${task.getTimestamp()}`);
        task.save('currentTask', { title: task.title, time: task.getTimestamp() });
        task.on('complete', () => task.log('任务完成'));
        task.emit('complete');
    </script>
</body>
</html> 